package com.moweilin.hello_server;

import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.streams.Pump;

/**
 * Created by moweilin on 2016/4/25.
 */
public class HtmlWriter {
    private HttpServerRequest request;
    private HttpServerResponse response;

    public HtmlWriter(HttpServerRequest request,HttpServerResponse response){
        this.request = request;
        this.response = response;
    }
    public static HtmlWriter create(HttpServerRequest request,HttpServerResponse response){
        return new HtmlWriter(request,response);
    }
    public void startHtml(){
        response.setChunked(true);
        response.write("<html><body>");
    }
    public  void writeRequestHeader(){
        response.write("<div><h3>request header</h3>");
        request.headers().forEach(entry -> {
            response.write(entry.getKey()+ " : " + entry.getValue() +"<br />");
        });
        response.write("</div>");
    }
    public  void writeResponseHeader(){
        response.write("<div><h3>response header</h3>");
        response.headers().forEach(entry -> {
            response.write(entry.getKey()+ " : " + entry.getValue() +"<br />");
        });
        response.write("</div>");
    }
    public void writeTitle(String title){
        response.write("<h3>" + title + "</h3>");
    }
    public void writeField(String key,String value){
        response.write(key + ": " + value +" <br />" );
    }
    public void writeField(String value){
        response.write( value +" <br />" );
    }

    public void startDiv(){
        response.write("div");
    }
    public void endDiv(){
        response.write("/div");
    }
    public void pump(){
        Pump pump = Pump.pump(request,response);
        request.endHandler(v->{
            endHtml();
            response.end();});
        pump.start();
    }

    public  void endHtml(){
        response.write("</body></html>");
    }
    public void end(){
        response.end();
    }
}
